package middleware

import (
    "net/http"

    "github.com/gin-gonic/gin"

    "github.com/samaa/photosalesplus/backend/internal/handlers"
    "github.com/samaa/photosalesplus/backend/internal/repositories"
)

type MerchantMiddleware struct {
    users repositories.UserRepository
}

func NewMerchantMiddleware(users repositories.UserRepository) *MerchantMiddleware {
    return &MerchantMiddleware{users: users}
}

func (m *MerchantMiddleware) RequireMerchant(c *gin.Context) {
    v, ok := c.Get("user_id")
    if !ok {
        c.AbortWithStatusJSON(http.StatusUnauthorized, handlers.APIResponse{Error: "未授权"})
        return
    }
    userID, _ := v.(uint)
    user, err := m.users.FindByID(c.Request.Context(), userID)
    if err != nil || user == nil || user.Role != "merchant" {
        c.AbortWithStatusJSON(http.StatusForbidden, handlers.APIResponse{Error: "需要商户权限"})
        return
    }
    c.Next()
}

